import { useMount, useUnmount } from "ahooks";
import markdownIt from "markdown-it";
import React, {
  PropsWithChildren,
  useImperativeHandle,
  useRef,
  useState,
} from "react";
import { sseRequest } from "../../api/sse";
import { Condition } from "@/components/Condition";

interface ISSEChatItemProps {
  className?: string;
  message: string;
  chatId: string;
  simple?: boolean;
  onLoading?: () => void;
  updateLoadingChat?: (markdown: string, answerType?: string) => void;
}

interface ISSeChatRef {
  abort: () => void;
}

function SSEChatItemFunction(
  props: PropsWithChildren<ISSEChatItemProps>,
  ref: React.Ref<ISSeChatRef>
) {
  const { onLoading, simple, message, chatId, updateLoadingChat } = props;
  const [state, setState] = useState("正在思考中...");
  const [finish, setFinish] = useState(false);
  const markdownText = useRef("");
  const markdownTextFinish = useRef(false);
  const index = useRef(0);
  const timer = useRef(0);
  const looping = useRef(false);
  const [text, setText] = useState("");
  const [answerType, setAnswerType] = useState("");
  const answerTypeRef = useRef("");
  const sseRequestRef = useRef(null);

  useImperativeHandle(ref, () => {
    return {
      abort() {
        sseRequestRef.current?.abort();
        clearTimeout(timer.current);
        return markdownText.current.slice(0, index.current);
      },
    };
  });

  useMount(() => {
    const md = new markdownIt();

    index.current = 0;

    const chat_id = chatId;
    const chat_message = message;

    sseRequestRef.current = sseRequest(
      "/node-api/chatStream",
      chat_message,
      chat_id,
      (res) => {
        const data = JSON.parse(res.data);
        console.log("data", data);
        const content =
          data?.choices?.[0]?.delta?.content?.answer ||
          data?.choices?.[0]?.delta?.content?.[0]?._source?.markdown_content ||
          data?.choices?.[0]?.delta?.content;
        markdownText.current += content;
        const finish_reason = data?.choices?.[0]?.finish_reason;
        if (finish_reason === "stop" && data?.is_good === "1") {
          setAnswerType("白话认证");
          answerTypeRef.current = "白话认证";
        } else if (finish_reason === "stop") {
          setAnswerType("大模型生成仅供参考");
          answerTypeRef.current = "大模型生成仅供参考";
        }
        markdownTextFinish.current = !!finish_reason;
        setState('正在为您生成回答')

        if (!looping.current) {
          looping.current = true;
          loopRenderText();
        }
      }
    );

    // mockSSEResponse((data) => {
    //   setState(data.status);
    //   markdownText.current = data.responseMarkdown;
    //   onLoading?.();

    //   if (!looping.current) {
    //     looping.current = true;
    //     loopRenderText();
    //   }
    // });

    function loopRenderText() {
      if (markdownText.current.length < index.current) {
        looping.current = false;
        if (markdownTextFinish.current) {
          updateLoadingChat(markdownText.current, answerTypeRef.current);
          setFinish(true);
        }
        return;
      }

      const text = md.render(markdownText.current.slice(0, index.current).replace(/([^\n])\n([^\n])/g, '$1\n\n$2'));

      setText(text);
      onLoading?.();

      timer.current = setTimeout(() => {
        index.current++;
        loopRenderText();
      }, 1000 / 20);
    }

    loopRenderText();
  });

  useUnmount(() => {
    sseRequestRef.current?.abort();
    clearTimeout(timer.current);
  });

  return (
    <div className="text-[16px] ml-[16px] text-justify break-all rounded-[16px] text-[#333] font-[400] markdownAnswer markdown-body overflow-hidden">
      <div className="flex flex-row gap-[16px] items-start relative">
        {!simple && <img src="/images/logo-mini.png" width={24} />}
        <div className="flex-1 min-w-0 flex flex-col">
          <Condition condition={!simple && !finish}>
            <div className="outPutAgentStatus">
              <img src="/images/loading.svg" className="LoadingCircle" />
              <div>{state}</div>
            </div>
          </Condition>
          <Condition condition={!!answerType}>
            <div className="absolute right-0 text-[#878aab] good-badge">
              {answerType}
            </div>
          </Condition>
          <div
            className={["w-full flex-1 min-w-0", "sail-markdown-flushing"]
              .filter(Boolean)
              .join(" ")}
            dangerouslySetInnerHTML={{ __html: text }}
          ></div>
        </div>
      </div>
    </div>
  );
}

export const SSEChatItem = React.forwardRef(SSEChatItemFunction);
